flickruploadr = {
}
flickruploadr.format_file_size = function(size, unit, min_unit){
  var min_unit = (typeof min_unit != undefined ? min_unit.toLowerCase() : "bytes");
  var unit = (typeof unit != undefined ? unit.toLowerCase() : null);
  var size_define = {
	bytes:{
		string: "bytes",
		scale:1,
		decimalPlaces:0
	},
	kb:{
		string: "kb",
		scale:1024,
		decimalPlaces:1
	},
	mb:{
		string: "mb",
		scale:1024*1024,
		decimalPlaces:2
	},
	gb:{
		string: "gb",
		scale:1024*1024*1024,
		decimalPlaces:2
	},
	decimal:".",
	result_format:"%number %units"
  };
  var min_unit_define = (size_define[min_unit] ? size_define[min_unit] : size_define.bytes);

  if(!unit){
  	unit = 'bytes';
  	var temp = size*min_unit_define.scale;
  	if(temp >= size_define.gb.scale){
  	  unit = 'gb';
	}else{
	  if(temp >= size_define.mb.scale){
		unit = 'mb';
	  }else{
		unit = 'kb';
	  }
	}
  }

  var unit_define = (size_define[unit] ? size_define[unit] : null);
  var scale = min_unit_define.scale/unit_define.scale;
  var final_size = (size*scale).toFixed(unit_define.decimalPlaces);
  if(final_size.substr(final_size.length-3) == '.00'){
  	final_size = final_size.substr(0, final_size.length-3);
  }

  if(final_size.substr(final_size.length-2) == '.0'){
  	final_size = final_size.substr(0, final_size.length-2);
  }
  var result = size_define.result_format.replace("%number", (final_size.toString().replace(".", size_define.decimal)));
  result = result.replace('%units', unit_define.string);
  return result;
}
console.log(flickruploadr.format_file_size(10000000, '', 'bytes'));
